package com.thesis.controller;

import com.thesis.common.CommonEnum;
import com.thesis.common.ResponseBean;
import com.thesis.entity.SysFile;
import com.thesis.entity.SysUser;
import com.thesis.service.FileService;
import com.thesis.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Anvy at 2020/2/1.
 */
@Controller
@RequestMapping({"file","ueditor"})
public class FileController {

    private static  final Logger logger= LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService fileService;

    @Autowired
    private UserService userService;

    @Value("${com.jane.file.baseFilePath}")
    private String baseFilePath;

    @Value("${com.jane.configjson.baseFilePath}")
    private String configJsonPath;

    /**
     * 文件上传
     * @param sysFile
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public ResponseBean fileUpload(SysFile sysFile, MultipartFile file){
        if(sysFile==null||file==null||file.isEmpty()){
            logger.debug("文件上传参数不对！");
            return new ResponseBean(false, CommonEnum.BAD_REQUEST);
        }
        SysFile uploadFile = fileService.saveOrUpdateFile(sysFile, file);

        if(uploadFile==null){
            return new ResponseBean(false,CommonEnum.BAD_REQUEST);
        }else{
            String categoryCode = sysFile.getCategoryCode();
            Long objectId = sysFile.getObjectId();
            if(categoryCode.equals("0000")){
                //说明用户头像
                SysUser sysUser=new SysUser();
                sysUser.setId(objectId);
                sysUser.setField1(uploadFile.getSaveName());
                userService.updateByPrimaryKeySelective(sysUser);
            }
            return  new ResponseBean(true,uploadFile,CommonEnum.SUCCESS_OPTION);
        }

    }

    /**
     * ueditor文件回显
     * @param request
     * @return
     */
    @RequestMapping("/jsp/upload")
    public ResponseEntity<byte[]> ueditorfileDown(HttpServletRequest request,String filePath){
        logger.debug("filePath:"+filePath);
        byte [] body = null;
        String rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static";
        String requestURL = request.getRequestURL().toString();
        if(requestURL.contains("127.0.0.1")||requestURL.contains("localhost")||requestURL.contains("192.168")){
            logger.debug("本地环境");
        }else{
            rootPath=configJsonPath;
        }
        String fileUrl=rootPath+ File.separator+filePath;
        try {
            //获取到文件流
            InputStream in = new FileSystemResource(fileUrl).getInputStream();
            body = new byte[in.available()];
            in.read(body);
        } catch (IOException e1) {
            logger.debug("文件读入出错，文件路径为："+fileUrl);
            e1.printStackTrace();
        }
        int index = filePath.lastIndexOf("/");
        String fileName = filePath.substring(index+1);
        logger.debug("本次下载的文件为："+fileName);
        //添加响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename="+fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }
    /**
     *
     * @param fileName--下载文件名
     * @param saveName--文件实际保存的名字
     * @return
     */
    @RequestMapping("/fileDown")
    public ResponseEntity<byte[]> fileDown(String saveName, String fileName){
        logger.debug("saveName:"+saveName);
        byte [] body = null;
        String fileUrl=baseFilePath+ File.separator+saveName;
        try {
            //获取到文件流
            InputStream in = new FileSystemResource(fileUrl).getInputStream();
            body = new byte[in.available()];
            in.read(body);
        } catch (IOException e1) {
            logger.debug("文件读入出错，文件路径为："+fileUrl);
            e1.printStackTrace();
        }
        if(StringUtils.isEmpty(fileName)){
            fileName=saveName;
        }
        //添加响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename="+fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }

    /**
     * 第二种文件下载/回显方法
     * @param id tb_sys_file.id
     * @param fileName  实际下载的文件名字
     * @return
     */
    @RequestMapping("/fileDown/{id}")
    public ResponseEntity<byte[]> fileDown(@PathVariable Long id, String fileName){
        SysFile sysFile = fileService.selectByPrimaryKey(id);
        byte [] body = null;
        String fileUrl=sysFile.getFileUrl();
        try {
            //获取到文件流
            InputStream in = new FileSystemResource(fileUrl).getInputStream();
            body = new byte[in.available()];
            in.read(body);
        } catch (IOException e1) {
            logger.debug("文件读入出错，文件路径为："+fileUrl);
            e1.printStackTrace();
        }
        //添加响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename="+fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }
}
